/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.h2psoft.truyen.tranh.activities;

import java.util.ArrayList;

import vn.persoft.extra.customview.CustomToast;
import vn.persoft.extra.internet.Internet;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.h2psoft.truyen.tranh.R;
import com.h2psoft.truyen.tranh.adapter.AdapterFragment;
import com.h2psoft.truyen.tranh.constants.Constants;
import com.h2psoft.truyen.tranh.dialog.LoadingDialog;
import com.h2psoft.truyen.tranh.objects.ObjChaper;
import com.h2psoft.truyen.tranh.server.ServerHandling;

public class ActivityInComic extends FragmentActivity implements OnClickListener, AnimationListener {
	private String tag = ActivityInComic.class.getCanonicalName();

	private Bundle bundle;
	private AdapterFragment mAdapter;
	private ArrayList<String> arrPagesUrls;
	private ArrayList<ObjChaper> temp;
	private Activity act;
	private LoadingDialog loadingDialog;
	private Button btnBack, btnNext, btnMenu, btnComment, btnDown, btnShare, btnBookmark;
	private LinearLayout lnBottomBar, lnNext, lnBack, lnMenu, lnBookmark;
	private boolean loadingMore;
	private Animation left_invi, right_invi, bottom_invi, bottom_visi, top_invi, left_visi, right_visi;
	private int targetPage = 0, start = 0, comicId = 0;

	private ViewPager mPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);
		act = this;
		getExtra();
		initView();
	}

	private void getExtra() {
		bundle = getIntent().getExtras();
		arrPagesUrls = bundle.getStringArrayList(Constants.KEY_ARRAY_URL);
		targetPage = bundle.getInt(Constants.KEY_TARGET_PAGE);
		comicId = bundle.getInt(Constants.KEY_COMIC_ID);
	}

	private void initView() {
		mPager = (ViewPager) findViewById(R.id.vpInComic);
		btnBack = (Button) findViewById(R.id.btnBack_activityIncomic);
		btnNext = (Button) findViewById(R.id.btnNext_activityIncomic);
		btnMenu = (Button) findViewById(R.id.btnMenu_activityInComic);
		btnComment = (Button) findViewById(R.id.btnComment_activityInComic);
		btnDown = (Button) findViewById(R.id.btnDown_activityInComic);
		btnShare = (Button) findViewById(R.id.btnShare_activityInComic);
		btnBookmark = (Button) findViewById(R.id.btnBookmark_activityIncomic);
		lnBottomBar = (LinearLayout) findViewById(R.id.lnBottomBar_activityInComic);
		lnBack = (LinearLayout) findViewById(R.id.lnBack_activityIncomic);
		lnNext = (LinearLayout) findViewById(R.id.lnNext_activityIncomic);
		lnMenu = (LinearLayout) findViewById(R.id.lnMenu_activityIncomic);
		lnBookmark = (LinearLayout) findViewById(R.id.lnBookmark_activityIncomic);
		left_invi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_left_invi);
		right_invi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_right_invi);
		bottom_invi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_bottom_invi);
		bottom_visi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_bottom_visi);
		top_invi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_top_invi);
		left_visi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_left_visi);
		right_visi = AnimationUtils.loadAnimation(act, R.anim.anima_transcale_right_visi);
		left_invi.setAnimationListener(this);
		left_visi.setFillAfter(true);
		right_invi.setAnimationListener(this);
		bottom_invi.setAnimationListener(this);
		bottom_visi.setFillAfter(true);
		top_invi.setFillAfter(true);
		btnBack.setOnClickListener(this);
		btnNext.setOnClickListener(this);
		btnBookmark.setOnClickListener(this);
		btnComment.setOnClickListener(this);
		btnDown.setOnClickListener(this);
		btnShare.setOnClickListener(this);
		btnMenu.setOnClickListener(this);
		mAdapter = new AdapterFragment(getSupportFragmentManager(), arrPagesUrls);
		loadingDialog = new LoadingDialog(act);
		mPager.setAdapter(mAdapter);
		mPager.setCurrentItem(targetPage);
		mPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {

				if (arg0 == (arrPagesUrls.size() / 2 - 1)) {
					loadListChaper(arg0);
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	// Copyright (C) 2011 - 2012 by PERSO STOCK COMPANY.
	private void loadListChaper(final int lastPage) {
		// if (lastPage == start)
		// return;
		if (start == 0) {
			start = lastPage + 1;
			Log.e(tag, "Start: " + start);
		}
		if (start % Constants.LOAD_COUNT == 0) {
			loadingDialog.show();
			if (Internet.isConnectedInternet(act))
				new Thread(new Runnable() {
					public void run() {
						synchronized (this) {
							if (!loadingMore) {
								loadingMore = true;
								try {
									ServerHandling getListChap = new ServerHandling();
									temp = new ArrayList<ObjChaper>();
									temp.clear();
									getListChap.getListChaper(temp, comicId, start);
								} catch (Exception e) {
									Log.e(tag, e.toString());
								}
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										loadingMore = false;
										loadingDialog.dismiss();
										start += temp.size();
										if (temp.size() != 0) {
											int tempSize = temp.size();
											for (int i = 0; i < tempSize; i++) {
												arrPagesUrls.add(temp.get(i).getImgUrl());
												arrPagesUrls.add(temp.get(i).getSecondImgUrl());
											}
											ArrayList<String[]> listPagesUrls = new ArrayList<String[]>();
											int size = arrPagesUrls.size();
											for (int i = 0; i < size; i++) {
												if (i % 2 == 0) {
													String[] imagesPerPage = { arrPagesUrls.get(i), arrPagesUrls.get(i + 1) };
													listPagesUrls.add(imagesPerPage);
												}
											}
											mAdapter.setListPagesUrls(listPagesUrls);
											mAdapter.setPageCount(arrPagesUrls.size() / 2);
											mAdapter.notifyDataSetChanged();
											mPager.setCurrentItem(lastPage);
											mPager.requestLayout();
										}
									}
								});
							}
						}
					}
				}).start();
			else {
				loadingDialog.dismiss();
				CustomToast.showRandom(act, R.string.dont_connect_internet);
			}
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack_activityIncomic:
			if (mPager.getCurrentItem() > 0)
				mPager.setCurrentItem(mPager.getCurrentItem() - 1, true);
			break;

		case R.id.btnNext_activityIncomic:
			try {
				mPager.setCurrentItem(mPager.getCurrentItem() + 1, true);
			} catch (Exception e) {
			}

			break;
		case R.id.btnShare_activityInComic:

			break;
		case R.id.btnComment_activityInComic:

			break;
		case R.id.btnDown_activityInComic:

			break;
		case R.id.btnMenu_activityInComic:
			if (lnBack.getVisibility() == View.GONE && lnBottomBar.getVisibility() == View.GONE) {
				lnBack.setVisibility(View.VISIBLE);
				lnNext.setVisibility(View.VISIBLE);
				lnBack.startAnimation(left_visi);
				lnNext.startAnimation(right_visi);
			} else if (lnBack.getVisibility() == View.VISIBLE && lnBottomBar.getVisibility() == View.GONE) {
				lnBottomBar.setVisibility(View.VISIBLE);
				lnBottomBar.startAnimation(bottom_visi);
			} else if (lnBack.getVisibility() == View.VISIBLE && lnBottomBar.getVisibility() == View.VISIBLE) {
				lnBack.startAnimation(left_invi);
				lnNext.startAnimation(right_invi);
				lnBottomBar.startAnimation(bottom_invi);
			}
			break;
		case R.id.btnBookmark_activityIncomic:
			Toast.makeText(act, R.string.saved_bookmark, Toast.LENGTH_SHORT).show();
			new Thread(new Runnable() {

				@Override
				public void run() {

					runOnUiThread(new Runnable() {
						public void run() {

						}
					});
				}
			}).start();
			break;
		}

	}

	@Override
	public void onAnimationEnd(Animation animation) {
		if (animation == left_invi)
			lnBack.setVisibility(View.GONE);
		if (animation == right_invi)
			lnNext.setVisibility(View.GONE);
		if (animation == bottom_invi)
			lnBottomBar.setVisibility(View.GONE);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

	}
}
